﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RATSharpW7.ViewModel;
using RATSharp.Model;
using System.Windows.Navigation;
using System.Windows.Data;
using System.ComponentModel;
using Microsoft.Phone.Shell;
using RATSharpW7.ViewModel.CalendarViewModel;
using System.Threading.Tasks;
using RATSharp.Rest;

namespace RATSharpW7.View
{
    /// <summary>
    /// Object profile screen with following actions:
    /// 1) object calendar
    /// 2) pick up object
    /// 3) favourite/unfavourite object buttons
    /// </summary>
    public partial class ObjectProfile : PhoneApplicationPage
    {

        ApplicationBarIconButton favouriteButton;
        ApplicationBarIconButton unfavouriteButton;
        bool isNewPageInstance = false;
        ObjectProfileViewModel model;

        public ObjectProfile()
        {
            InitializeComponent();

            isNewPageInstance = true;
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode !=
                  System.Windows.Navigation.NavigationMode.Back)
            {
                State["ObjectProfileViewModel"] = model;
            }
        }


        private void handleModelChanged(object sender, EventArgs e)
        {
            
            bool isFavourite = (sender as ObjectProfileViewModel).DataSource.favourite;
            ApplicationBarIconButton toRemove = isFavourite ? favouriteButton : unfavouriteButton;
            if (this.ApplicationBar.Buttons.Contains(toRemove))
            {
                this.ApplicationBar.Buttons.Remove(toRemove);
            }
            this.ApplicationBar.Buttons.Add(!isFavourite ? favouriteButton : unfavouriteButton);
        }

        private void initActionBar()
        {
            this.ApplicationBar = new ApplicationBar();
            this.ApplicationBar.IsVisible = true;
            this.ApplicationBar.Opacity = 1;
            favouriteButton = new ApplicationBarIconButton(new Uri("/Images/addtofavs.png", UriKind.RelativeOrAbsolute));
            favouriteButton.Text = Application.Current.Resources["FavouriteButtonLabel"] as string;
            favouriteButton.Click += new EventHandler(handleFavouriteButtonClick);
            
            unfavouriteButton = new ApplicationBarIconButton(new Uri("/Images/removefromfavs.png", UriKind.RelativeOrAbsolute));
            unfavouriteButton.Text = Application.Current.Resources["UnfavouriteButtonLabel"] as string;
            unfavouriteButton.Click += new EventHandler(handleUnfavouriteButtonClick);

            ApplicationBarIconButton calendarButton = new ApplicationBarIconButton(new Uri("/Images/gotodate.png", UriKind.RelativeOrAbsolute));
            calendarButton.Text = Application.Current.Resources["CalendarButtonLabel"] as string;
            calendarButton.Click += new EventHandler(handleCalendarButtonClick);
            this.ApplicationBar.Buttons.Add(calendarButton);

            if (model.DataSource.pickable)
            {
                ApplicationBarIconButton pickUpButton = new ApplicationBarIconButton(new Uri("/Images/pickup.png", UriKind.RelativeOrAbsolute));
                pickUpButton.Text = Application.Current.Resources["PickUpLabel"] as string;
                pickUpButton.Click += new EventHandler(handlePickUpButtonClick);
                this.ApplicationBar.Buttons.Add(pickUpButton);
            }

            model.PropertyChanged += new PropertyChangedEventHandler(handleModelChanged);
            handleModelChanged(model, new EventArgs());
        }

        private void handlePickUpButtonClick(object sender, EventArgs e)
        {
            Task<Reservations> task = RestService.getInstance().pickUpObject(model.DataSource.id);

            task.ContinueWith(t =>
            {

                Reservations list = t.Result;
                Exception ex = t.Exception;

                //switch to UI thread
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    if (ex != null)
                    {
                        ViewUtils.reportError(ex != null ? ex.Message : "unknown");
                    }

                    else if (list.Count > 0)
                    {
                        ViewUtils.reportMessage(Application.Current.Resources["MessageObjectPicked"] as string);
                        return;
                    }
                    else
                    {
                        RATSharp.Model.ReservationFactory.CreateReservationData data = new RATSharp.Model.ReservationFactory.CreateReservationData();
                        data.obj = model.DataSource;
                        data.selectedDate = DateTime.Now;
                        data.pickAction = PickAction.PICKED;
                        NavigationService.Navigate("View", typeof(CreatePickUpReservation), data);
                    }
                });
            });
        }

        private void handleCalendarButtonClick(object sender, EventArgs e)
        {
            NavigationService.Navigate("View", typeof(Calendar), new CalendarObjectDataFactory(UserViewModel.UserContext.Id, model.DataSource.id));
        }


        private void handleFavouriteButtonClick(object sender, EventArgs e)
        {
            model.favouriteChange(true);
        }

        private void handleUnfavouriteButtonClick(object sender, EventArgs e)
        {
            model.favouriteChange(false);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (isNewPageInstance)
            {
                if (model == null)
                {
                    if (State.ContainsKey("ObjectProfileViewModel"))
                    {
                        MessageBox.Show("Retrieving state...");
                        model = State["ObjectProfileViewModel"]
                                           as ObjectProfileViewModel;
                    }
                    else
                    {
                        var data = NavigationContext.GetData<RATSharp.Model.Object>();

                        model = new ObjectProfileViewModel(data);
                    }
                }
                DataContext = model;
            }
            isNewPageInstance = false;
            initActionBar();
        }

    }
}